#-----------------------------#
# coding='utf-8'
# !Python3
# 使用 Flask-SQLAlchemy 创建数据库程序
#-----------------------------#


from constants import DB_URI

from flask_sqlalchemy import SQLAlchemy
from flask import Flask,render_template,url_for,request
from werkzeug.wrappers import Response




# 配置声明
app = Flask(__name__) 
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False # 取消警告提醒
app.config.update(debug=True,SECRET_KEY="terry's website")  # 设计时就指定启动模式

#app.config.from_object(constants) #怎么用
#app.config.from_pyfile('settings.py',silent=True)  #怎么用
#region --数据库应用

#数据库初始化：
db = SQLAlchemy(app)

#ORM 类
class User(db.Model):
  id = db.Column(db.Integer,primary_key=True)
  username = db.Column(db.String(50),unique=True)
  email = db.Column(db.String(50),unique=True)
  def __init__(self,username,email):
      self.username = username
      self.email = email
  def __repr__(self):
      return '<User %d,%s,%s>' % (self.id,self.username,self.email)

class Movie(db.Model):		                        #表名将会是	movie
    id = db.Column(db.Integer,primary_key=True)
    title = db.Column(db.String(60))
    year = db.Column(db.String(4))
# 映射模型到数据库表
# Flask-SQLAlchemy会自动将类名小写化，然后映射成表名。
db.create_all()

# 添加数据， 相比使用sqlalchemy, 添加数据和之前的没有区别，只是session成为了一个db的属性
"""
admin = User('admin','admin@example.com')
guest = User('guest','guest@example.com')
db.session.add(admin)
db.session.add(guest) 
db.session.commit()
"""

# 查询数据
""" users = User.query.all()
print(type(users))
for x in users:
    print(x)
 """

#i = User.query.filter(User.username=='admin').first()
#print(i)

# 删除数据
""" i = User.query.filter(User.username=='admin').first()
db.session.delete(i)
db.session.commit() """

#endregion

#region --网页路由

@app.route('/')
@app.route('/index/')
def index():
    return { "msg":"hello flask newbie"} # 返回字符串
    #return render_template('index.html') #返回模板
    #当你的模板中要传递的参数过多的时候，用字典进行包装，并且加两个*号，来转换成关键字参数
    #return render_template('index.html',**{'user':'xiaotuo})

@app.route('/form1/',methods=['GET','POST'])
def form1():
    if request.method=='POST':
        title=request.form.get('title')
        year=request.form.get('year')
        return render_template('form_1.html')
        if not title or year or len(year)>4 or len(title)>60:
            flash("Invalid input")
            return redirect(url_for('form1'))
        movie=Movie(title=title,year=year)
        db.session.add(movie)
        db.session.commit()
        flash('Item created')
        return redirect(url_for('form1'))
    user=User.query.first()
    movies=Movie.query.all()
    return render_template('form_1.html',user=user,movies=movies)

#endregion

#region --重写flask的响应方法，使之返回json字符串
class JSONResponse(Response):
     default_mimetype = 'application/json'

     @classmethod
     def force_type(cls,response,environ=None):
         if isinstance(response,dict):
             response = jsonify(response)
         return super(JSONResponse,cls).force_type(response,environ)

app.response_class = JSONResponse
#endregion


if __name__ == '__main__':
    #app.debug=True #运行时指定模式,不安全
    app.run(debug=True)